package com.demo.javaDemo.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateTimeUtil {

	/**
	 * 将日期转化为对应格式的String
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDateTime(Date date, String format) {
		java.text.DateFormat dfm = new java.text.SimpleDateFormat(format);
		if (date != null) {
			return dfm.format(date);
		} else {
			return "";
		}
	}
	
	/**
	 * 日期格式化, 格式:yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static String formatDateTime(Date date) {
		return formatDateTime(date, "yyyy-MM-dd HH:mm:ss");
	}
	/**
	 *	日期格式化, 格式:yyyy-MM-dd
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
		return formatDateTime(date, "yyyy-MM-dd");
	}
	
	/**
	  * 解释
	 * @param date
	 * @param fm
	 * @return
	 */
	public static Date parseDateTime(String date, String fm) {
		Date d = null;
		try {
			d = new java.text.SimpleDateFormat(fm).parse(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d;
	}
	
	/**
	 * 转日期,格式:yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static Date parseDateTime(String date) {
		return parseDateTime(date, "yyyy-MM-dd HH:mm:ss");
	}
	
	public static Date parseDate(String date) {
		return parseDateTime(date, "yyyy-MM-dd");
	}
	
 
    /**
     * LocalDateTime转换为Date
     * @param localDateTime
     */
    public static Date toDate(LocalDateTime  localDateTime){
        ZoneId zoneId = ZoneId.systemDefault(); // 时区
        ZonedDateTime zdt = localDateTime.atZone(zoneId);//带时区时间
        Instant instant=zdt.toInstant();
        return Date.from(instant);
    }
    
    
    /**
     * Date转换为LocalDateTime
     * @param date
     */
    public static void date2LocalDateTime(Date date){
        Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
        ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
 
        System.out.println(localDateTime.toString());//2018-03-27T14:07:32.668
        System.out.println(localDateTime.toLocalDate() + " " +localDateTime.toLocalTime());//2018-03-27 14:48:57.453
 
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//This class is immutable and thread-safe.@since 1.8
        System.out.println(dateTimeFormatter.format(localDateTime));//2018-03-27 14:52:57
    }
}
